package com.heima.article.service.impl;

import com.aliyuncs.ram.model.v20150501.CreateUserRequest;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import com.sun.jersey.json.impl.provider.entity.JSONArrayProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
@Transactional
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Resource
    AuthorMapper authorMapper;
    @Resource
    ApArticleConfigMapper apArticleConfigMapper;
    @Resource
    ApArticleContentMapper apArticleContentMapper;
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        // 存储三张表的信息
        if (articleDto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 封装ApArticle文章对象
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto,apArticle);
        // 存储作者id
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, articleDto.getAuthorName()));
//        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        if (apAuthor == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"作者信息不存在");
        }
        apArticle.setAuthorName(apAuthor.getName());
        // 如果文章id为null添加文章
        if (apArticle.getId() == null){
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            save(apArticle);
        }else {
            // 修改文章
            // 修改前删除之前的配置和内容
            ApArticle article = getById(articleDto.getId());
            if (article == null){
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId,apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId,apArticle.getId()));
            updateById(apArticle);
        }
        //添加文章配置
        //保存article_config 数据
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfigMapper.insert(apArticleConfig);
        //添加文章内容
        //保存文章article_content 数据
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(articleDto.getContent());
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContentMapper.insert(apArticleContent);
        //返回文章ID
        return ResponseResult.okResult(apArticle.getId());

    }

    @Resource
    ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    String webSite;
    @Override
    // 加载app页面
    public ResponseResult load(Short loadType, ArticleHomeDto dto) {
        // 检查参数
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 判断页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0){
            dto.setSize(10);
        }
        // 判断条件
        if (StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 判断时间
        if (dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        if(dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        // 判断是找最新的，还是查询更多信息
        if (!loadType.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadType.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadType = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        // 执行查询
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadType);

        // 返回结果
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(webSite);
        return responseResult;
    }


    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        // 加载文章内容信息
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 查询文章配置信息
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getArticleId, dto.getArticleId()));
        if (apArticleConfig == null ) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章缺少配置信息");
        }
        if (apArticleConfig.getIsDelete() || apArticleConfig.getIsDown()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已经下架");
        }
        // 查询文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, dto.getArticleId()));
        if (apArticleContent == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章内容不存在");
        }
        // 封装返回结果
        Map map = new HashMap<String,Object>();
        map.put("config",apArticleConfig);
        map.put("content",apArticleContent);
        return ResponseResult.okResult(map);

    }

    @Autowired
    private BehaviorFeign behaviorFeign;
    @Autowired
    private UserFeign userFeign;

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //1 参数校验
        if(dto == null || dto.getArticleId() == null || dto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        boolean iscollection=false,isfollow=false;

        // 是否关注
        ApAuthor apAuthor = authorMapper.selectById(dto.getAuthorId());
        if(apAuthor!=null){
            ApUserFollow apUserFollow = userFeign.findByUserIdAndFollowId(
                    AppThreadLocalUtils.getUser().getId(), apAuthor.getUserId());
            if(apUserFollow!=null){
                isfollow=true;
            }
        }

        // 是否点赞/不喜欢
        ApArticleRelationDto relationDto = new ApArticleRelationDto();
        relationDto.setArticleId(dto.getArticleId());
        relationDto.setEntryId(AppThreadLocalUtils.getUser().getId());
        relationDto.setType((short) 1);
        Map behaviorMap = behaviorFeign.findApArticleRelation(relationDto);


        //3 返回结果
        Map resultMap = new HashMap();
        resultMap.put("isfollow", isfollow);
        resultMap.put("iscollection", iscollection);
        resultMap.putAll(behaviorMap);

        return ResponseResult.okResult(resultMap);
    }
}